//
//  SAlertView.m
//  SAlterView
//
//  Created by Samuel on 15/9/1.
//  Copyright (c) 2015年 Samuel. All rights reserved.
//

#import "SAlertView.h"
#import "AppDelegate.h"

#define kUIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


const int message_interval = 30;
const int title_interval = 15;
const int button_interval = 15;

@interface SAlertView()


@property (strong,nonatomic)UIView *bgView;

@end

@implementation SAlertView
{
    UILabel *titleLabel;
    UILabel *messageLabel;
    UIButton *cancelButton;
    UIButton *confirmButton;
    
    NSMutableArray *buttons;
    
    UITapGestureRecognizer *closees;
}


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[[UIColor blackColor]colorWithAlphaComponent:.2]];
        buttons = [NSMutableArray array];
    }
    return self;
}
#pragma mark - Default_SAlterView
/**
 *  默认SalterView
 *
 *  @param title               titleString
 *  @param message             messageString(默认最高300)
 *  @param delegate            代理
 *  @param cancelButtonTitle   取消
 *  @param confirmButtonTitles 确定
 *
 *  @return
 */
- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
                     delegate:(id /*<UIAlertViewDelegate>*/)delegate
            cancelButtonTitle:(NSString *)cancelButtonTitle
          confirmButtonTitles:(NSString *)confirmButtonTitles;
{
    self = [self initWithFrame:[UIScreen mainScreen].bounds];//
    self.delegate = delegate;
    [self setDefaultAlterView:title andMessage:message andCancelButton:cancelButtonTitle andConfirmButton:confirmButtonTitles];
    return self;
}
- (void)setDefaultAlterView:(NSString *)titles
                 andMessage:(NSString*)messages
            andCancelButton:(NSString*)cancelButtonstitles
           andConfirmButton:(NSString*)confirmButtontiles
{
    titleLabel = (titleLabel)?titleLabel:[[UILabel alloc]init];
    messageLabel = (messageLabel)?messageLabel:[[UILabel alloc]init];
    cancelButton = (cancelButton)?cancelButton:[UIButton buttonWithType:UIButtonTypeCustom];
    confirmButton = (confirmButton)?confirmButton:[UIButton buttonWithType:UIButtonTypeCustom];
    UILabel *line;
    
    self.bgView = (self.bgView)?self.bgView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, 250, 0)];
    [self. bgView setBackgroundColor:[UIColor whiteColor]];
    self.bgView.layer.masksToBounds = YES;
    self.bgView.layer.cornerRadius = 5;
    self.bgView.userInteractionEnabled = YES;
    
    if (titles!=nil && ![titles isEqualToString:@""]) {
        titleLabel.text = titles;
        [titleLabel setFont:[UIFont systemFontOfSize:14]];
        [titleLabel setTextColor:[UIColor darkGrayColor]];
        [titleLabel sizeToFit];
        [titleLabel setCenter:CGPointMake(CGRectGetWidth(self.bgView.frame)/2, title_interval+CGRectGetHeight(titleLabel.frame)/2)];
        
        line = [[UILabel alloc]initWithFrame:CGRectMake(10, 2*title_interval+CGRectGetHeight(titleLabel.frame), CGRectGetWidth(self.bgView.frame)-20, 0.5)];
        [line setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        [self.bgView  addSubview:titleLabel];
        [self.bgView  addSubview:line];
    }
    
    
    
    messageLabel.text = messages;
    [messageLabel setFont:[UIFont systemFontOfSize:13]];
    [messageLabel setTextColor:[UIColor darkTextColor]];
    [messageLabel setNumberOfLines:0];
    [messageLabel setFrame:CGRectMake(0, 0, 220, 0)];
    [messageLabel sizeToFit];
    if (CGRectGetHeight(messageLabel.frame)>=300) {
        [messageLabel setFrame:CGRectMake(0, 0, 220, 300)];
    }
    [messageLabel setCenter:CGPointMake(self.bgView.center.x, message_interval+line.frame.origin.y+CGRectGetHeight(messageLabel.frame)/2)];
    
    UIView *buttonViewBg = [[UIView alloc]initWithFrame:CGRectMake(0, messageLabel.frame.origin.y+CGRectGetHeight(messageLabel.frame), CGRectGetWidth(self.bgView.frame), 75)];
    [buttonViewBg setBackgroundColor:[UIColor whiteColor]];
    
    [cancelButton setTitle:cancelButtonstitles forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [cancelButton setTitleColor:kUIColorFromRGB(0x79BA3B) forState:UIControlStateNormal];
    [cancelButton setFrame:CGRectMake(CGRectGetWidth(self.bgView.frame)/2-((confirmButtontiles==nil)?50:110), 30, 100, 30)];
    [cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchDown];
    cancelButton.layer.masksToBounds = YES;
    cancelButton.layer.cornerRadius = 3;
    cancelButton.layer.borderWidth = 1;
    cancelButton.layer.borderColor = kUIColorFromRGB(0x79BA3B).CGColor;
    [cancelButton setBackgroundColor:[UIColor whiteColor]];
    [buttonViewBg  addSubview:cancelButton];
    
    if (confirmButtontiles!=nil ) {
        [confirmButton setTitle:confirmButtontiles forState:UIControlStateNormal];
        [confirmButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [confirmButton setFrame:CGRectMake(CGRectGetWidth(self.bgView.frame)/2+10, 30, 100, 30)];
        [confirmButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchDown];
        confirmButton.layer.masksToBounds = YES;
        confirmButton.layer.cornerRadius = 3;
        confirmButton.layer.borderWidth = 1;
        confirmButton.layer.borderColor = kUIColorFromRGB(0x79BA3B).CGColor;
        [confirmButton setBackgroundColor:kUIColorFromRGB(0x79BA3B)];
        [buttons addObject:confirmButton];
        [buttonViewBg  addSubview:confirmButton];
    }
    int buttonViewBgheight = CGRectGetHeight(buttonViewBg.frame);
    int messageLabelheight = CGRectGetHeight(messageLabel.frame);
    int titleLabelheight = CGRectGetHeight(titleLabel.frame);
    int title_interval_i = title_interval/((titles==nil || [titles isEqualToString:@""])?2:0.5);
    int message_interval_i = message_interval/((titles == nil ||[titles isEqualToString:@""])?1.5:1);
    [self.bgView setFrame:CGRectMake(self.bgView.frame.origin.x, self.bgView.frame.origin.y, 250, buttonViewBgheight+messageLabelheight+titleLabelheight+message_interval_i+title_interval_i)];
    [self.bgView setCenter:self.center];
    
    
    [self.bgView  addSubview:messageLabel];
    [self.bgView  addSubview:buttonViewBg];
    
    
    [self addSubview:self.bgView];
    
}
#pragma mark - Coustom_SAlterView
/**
 *  自定义SAlterView
 *
 *  @param centerView    中间显示的View
 *  @param point       自定义位置
 *  @param delegate      代理
 *  @param cancelButtons 取消按钮
 *  @param ortherButton  其他按钮
 *
 *  @return
 */
- (instancetype)initWithView:(UIView *)centerView
                coustomPoint:(CGPoint)point
                    delegate:(id /*<UIAlertViewDelegate>*/)delegate
                cancelButton:(UIButton *)cancelButtons
                ortherButton:(UIButton *)ortherButton, ... NS_REQUIRES_NIL_TERMINATION;
{
    self = [self initWithFrame:[UIScreen mainScreen].bounds];//
    self.delegate = delegate;
    self.bgView = (self.bgView)?self.bgView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(centerView.frame), CGRectGetHeight(centerView.frame))];
    
    [self. bgView setBackgroundColor:[UIColor whiteColor]];
    self.bgView.layer.masksToBounds = YES;
    self.bgView.layer.cornerRadius = 5;
    [centerView setCenter:self.bgView.center];
    [self.bgView addSubview:centerView];
    
    [self.bgView setCenter:point];
    [self addSubview:self.bgView];
    
    cancelButton = cancelButtons;
    [cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchDown];
    
    if (ortherButton) {
        [buttons addObject:ortherButton];
        [ortherButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchDown];
        
    }
    va_list arguments;
    va_start(arguments, ortherButton);
    UIButton *getOrtherButton;
    if(ortherButton)
    {
        while((getOrtherButton = va_arg(arguments,UIButton *)))
        {
            if (getOrtherButton) {
                [buttons addObject:getOrtherButton];
                [getOrtherButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchDown];
            }
        }
    }
    va_end(arguments);
    
    
    
    return self;

}
/**
 *  自定义SAlterView
 *
 *  @param centerView    中间显示的View
 *  @param delegate      代理
 *  @param cancelButtons 取消按钮
 *  @param ortherButton  其他按钮
 *
 *  @return
 */
- (instancetype)initWithView:(UIView *)centerView
                    delegate:(id /*<UIAlertViewDelegate>*/)delegate
                cancelButton:(UIButton *)cancelButtons
                ortherButton:(UIButton *)ortherButton, ... NS_REQUIRES_NIL_TERMINATION;
{
    self = [self initWithFrame:[UIScreen mainScreen].bounds];//
    self.delegate = delegate;
    self.bgView = (self.bgView)?self.bgView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(centerView.frame), CGRectGetHeight(centerView.frame))];
    
    [self. bgView setBackgroundColor:[UIColor whiteColor]];
    self.bgView.layer.masksToBounds = YES;
    self.bgView.layer.cornerRadius = 5;
    [centerView setCenter:self.bgView.center];
    [self.bgView addSubview:centerView];
    
    [self.bgView setCenter:self.center];
    [self addSubview:self.bgView];
    
    cancelButton = cancelButtons;
    [cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchDown];
    
    if (ortherButton) {
        [buttons addObject:ortherButton];
        [ortherButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchDown];

    }
    va_list arguments;
    va_start(arguments, ortherButton);
    UIButton *getOrtherButton;
    if(ortherButton)
    {
        while((getOrtherButton = va_arg(arguments,UIButton *)))
        {
            if (getOrtherButton) {
                [buttons addObject:getOrtherButton];
                [getOrtherButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchDown];
            }
        }
    }
    va_end(arguments);
    
    
    
    return self;
}
#pragma mark - ButtonAction
/**
 *  显示
 */
- (void)show;
{
    NSEnumerator *frontToBackWindows = [[[UIApplication sharedApplication]windows]reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows)
    {
        if (window.windowLevel == UIWindowLevelNormal) {
            [self setCenter:window.center];
            self.alpha = 0;
            [window addSubview:self];
            [UIView animateWithDuration:.2 animations:^{
                self.alpha = 1;
            }];
            
            break;
        }
    }
}
/**
 *  隐藏
 */
- (void)dismiss;
{
    [UIView animateWithDuration:.2 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
-(void)setOpenTapBackgroundToDismiss:(BOOL )openTapBackgroundToDismiss
{
    _openTapBackgroundToDismiss = openTapBackgroundToDismiss;
    if (openTapBackgroundToDismiss) {
        closees = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissWithTap:)];
        [self addGestureRecognizer:closees];
    }
    else
    {
        [closees removeTarget:self action:@selector(dismiss)];
    }
}
- (void)dismissWithTap:(UITapGestureRecognizer*)sender
{
    CGPoint point = [sender locationInView:self];
    UIView *getView = [self.subviews objectAtIndex:0];
    if (point.x<(getView.frame.origin.x+CGRectGetWidth(getView.frame))&&
        point.x>getView.frame.origin.x&&
        point.y<(getView.frame.origin.y+CGRectGetHeight(getView.frame))&&
        point.y>getView.frame.origin.y) {
        
    }
    else
    {
        [self dismiss];
    }
}
#pragma mark - SAlterViewDelegate 代理回调
- (void)cancelButton:(UIButton*)sender
{
    if ([self.delegate respondsToSelector:@selector(sAlertView:clickedButtonAtIndex:)]) {
        [self.delegate sAlertView:self clickedButtonAtIndex:0];
    }
    [self dismiss];
    
}
- (void)confirmButton:(UIButton*)sender
{
    if ([self.delegate respondsToSelector:@selector(sAlertView:clickedButtonAtIndex:)]) {
        [self.delegate sAlertView:self clickedButtonAtIndex:[buttons indexOfObject:sender]+1];
    }
}
@end




